-module(homework_manager).
-export([create_homework/4, get_list_homework_to_do/2, answered/4, get_list_homework_to_correct/2, corrected/5, get_list_homework_to_rate/2, rated/6, get_list_homework_finished/2]).
-include("records.hrl").


% This function create a new homework adding it to the database and sending a message to the
% user that receives the  homework
create_homework(Cookie, Student, Question, Difficulty) ->
	{ok, Session} = yaws_api:cookieval_to_opaque(Cookie),
	case db_homework:insert(Session#session.user, Student, Question, Difficulty) of
		{atomic, Id} ->
			case db_homework_to_do:insert(Student, Id) of
				{atomic, ok} ->
					homework_router:send(Student, homework_to_do),
					ok;
				_ ->
					error
			end;
		_ ->
			error
	end.
	
	
% This function returns a list that contains the homework to do of a user.
% The elements on the list are in the interval [offset, offset+5]
get_list_homework_to_do(Username, Offset) ->
	{atomic, ToDo} = db_homework_to_do:get(Username),
	TotalToDo = length(ToDo),
		
	if TotalToDo =:= 0 ->
		{array, [TotalToDo | []]};
	true ->
		% Obtain the list of homeworks ID
		LIds = [Id || Id <-db_homework_to_do:get_with_offset(Username, Offset, TotalToDo)],
	
		% Obtain the all the data about every homework ID
		LHomeworks = lists:map(fun(X) -> db_homework:get(X) end, lists:reverse(LIds)),
	
		% Obtain from the list of homeworks the information that interests us
		Data = [ {struct, [
			{id, integer_to_list(Id)}, 
			{question, Question}, 
			{difficulty, Difficulty}, 
			{day, integer_to_list(Day)}, 
			{month, integer_to_list(Month)},
			{year, integer_to_list(Year)}, 
			{hour, integer_to_list(Hour)}, 
			{minute, integer_to_list(Minute)}, 
			{teacher, atom_to_list(Teacher)}]}
			|| {atomic, 
				[{homework, Id, Question, _, _, _, Difficulty, _, 
				{{Year, Month, Day}, {Hour, Minute, _}}, Teacher, _}]} <- LHomeworks],
			
		{array, [TotalToDo | Data]}
	end.
	
	
% This function adds the answer to the ID homework. Then removes the homework from homework_to_do
% and insert it in homework_to_correct
answered(Cookie, Id, Teacher, Answer) ->
	{ok, Session} = yaws_api:cookieval_to_opaque(Cookie),
	case db_homework_to_do:delete(Session#session.user, Id) of
		{atomic, ok} ->
			case db_homework_to_correct:insert(Teacher, Id) of
				{atomic, ok} ->
					db_homework:add_answer(Id, Answer),
					homework_router:send(Teacher, homework_to_correct),
					NewSession = Session#session{homework_to_do = Session#session.homework_to_do - 1},
					yaws_api:replace_cookie_session(Cookie, NewSession),
					ok;
				_ ->
					error
			end;
		_ ->
			error
	end.
	

% This function returns a list that contains the homework to correct of a user.
% The elements on the list are in the interval [offset, offset+5]
get_list_homework_to_correct(Username, Offset) ->
	{atomic, ToCorrect} = db_homework_to_correct:get(Username),
	TotalToCorrect = length(ToCorrect),
		
	if TotalToCorrect =:= 0 ->
		{array, [TotalToCorrect | []]};
	true ->
		% Obtain the list of homeworks ID
		LIds = [Id || Id <-db_homework_to_correct:get_with_offset(Username, Offset, TotalToCorrect)],
	
		% Obtain all the data about every homework ID
		LHomeworks = lists:map(fun(X) -> db_homework:get(X) end, lists:reverse(LIds)),
	
		% Obtain from the list of homeworks the information that interests us
		Data = [ {struct, [
			{id, integer_to_list(Id)}, 
			{question, Question},
			{answer, Answer},
			{difficulty, Difficulty}, 
			{day, integer_to_list(Day)}, 
			{month, integer_to_list(Month)},
			{year, integer_to_list(Year)}, 
			{hour, integer_to_list(Hour)}, 
			{minute, integer_to_list(Minute)}, 
			{student, atom_to_list(Student)}]}
			|| {atomic, 
				[{homework, Id, Question, Answer, _, _, Difficulty, _, 
				{{Year, Month, Day}, {Hour, Minute, _}}, _, Student}]} <- LHomeworks],
			
		{array, [TotalToCorrect | Data]}
	end.
	
	
% This function adds the correction and mark to the ID homework. Then removes the homework from homework_to_correct
% and insert it in homework_to_rate
corrected(Cookie, Id, Student, Correction, Mark) ->
	{ok, Session} = yaws_api:cookieval_to_opaque(Cookie),
	case db_homework_to_correct:delete(Session#session.user, Id) of
		{atomic, ok} ->
			case db_homework_to_rate:insert(Student, Id) of
				{atomic, ok} ->
					db_homework:add_correction(Id, Correction),
					db_homework:add_mark(Id, Mark),
					homework_router:send(Student, homework_to_rate),
					NewSession = Session#session{homework_to_correct = Session#session.homework_to_correct - 1},
					yaws_api:replace_cookie_session(Cookie, NewSession),
					ok;
				_ ->
					error
			end;
		_ ->
			error
	end.
	
	
% This function returns a list that contains the homework to rate of a user.
% The elements on the list are in the interval [offset, offset+5]
get_list_homework_to_rate(Username, Offset) ->
	{atomic, ToRate} = db_homework_to_rate:get(Username),
	TotalToRate = length(ToRate),
		
	if TotalToRate =:= 0 ->
		{array, [TotalToRate | []]};
	true ->
		% Obtain the list of homeworks ID
		LIds = [Id || Id <- db_homework_to_rate:get_with_offset(Username, Offset, TotalToRate)],
	
		% Obtain all the data about every homework ID
		LHomeworks = lists:map(fun(X) -> db_homework:get(X) end, lists:reverse(LIds)),
	
		% Obtain from the list of homeworks the information that interests us
		Data = [ {struct, [
			{id, integer_to_list(Id)}, 
			{question, Question},
			{answer, Answer},
			{correction, Correction},
			{difficulty, Difficulty},
			{mark, Mark}, 
			{day, integer_to_list(Day)}, 
			{month, integer_to_list(Month)},
			{year, integer_to_list(Year)}, 
			{hour, integer_to_list(Hour)}, 
			{minute, integer_to_list(Minute)}, 
			{teacher, atom_to_list(Teacher)}]}
			|| {atomic, 
				[{homework, Id, Question, Answer, Correction, _, Difficulty, Mark, 
				{{Year, Month, Day}, {Hour, Minute, _}}, Teacher, _}]} <- LHomeworks],
			
		{array, [TotalToRate | Data]}
	end.
	
	
% This function adds the rating to the ID homework. Then removes the homework from homework_to_rate
% and insert it in homework_finished
rated(Cookie, Id, Teacher, Rating, Mark, Difficulty) ->
	{ok, Session} = yaws_api:cookieval_to_opaque(Cookie),
	case db_homework_to_rate:delete(Session#session.user, Id) of
		{atomic, ok} ->
			case db_homework_finished:insert(Session#session.user, Id) of
				{atomic, ok} ->
					db_homework:add_rating(Id, Rating),
					
					% Update the user row in the users table
					{atomic, [{user, _, Name, _, _, _, _, _, _, _, HDone, _, _, _, _, Level}]} = db_user:get_user(Session#session.user),
					{ok, [MarkInt], _} = io_lib:fread("~d", Mark),
					{ok, [DifficultyInt], _} = io_lib:fread("~d", Difficulty),
					{ok, [RatingInt], _} = io_lib:fread("~d", Rating),
					NewLevel = (HDone / (HDone + 1)) * Level + (1 / (HDone + 1)) * MarkInt * DifficultyInt * 0.1,
					db_user:add_homework_done(Name, NewLevel),
					
					% Send a message to the teacher
					homework_router:send(Teacher, {homework_finished, RatingInt}),
					
					% Update the session
					NewSession = Session#session{
						homework_to_rate = Session#session.homework_to_rate - 1,
						homework_done = HDone + 1,
						level = NewLevel},
					yaws_api:replace_cookie_session(Cookie, NewSession),
					ok;
				_ ->
					error
			end;
		_ ->
			error
	end.
	

% This function returns a list that contains the finished homework of a user.
% The elements on the list are in the interval [offset, offset+5]
get_list_homework_finished(Username, Offset) ->
	{atomic, Finished} = db_homework_finished:get(Username),
	TotalFinished = length(Finished),
		
	if TotalFinished =:= 0 ->
		{array, [TotalFinished | []]};
	true ->
		% Obtain the list of homeworks ID
		LIds = [Id || Id <- db_homework_finished:get_with_offset(Username, Offset, TotalFinished)],
	
		% Obtain all the data about every homework ID
		LHomeworks = lists:map(fun(X) -> db_homework:get(X) end, lists:reverse(LIds)),
	
		% Obtain from the list of homeworks the information that interests us
		Data = [ {struct, [
			{id, integer_to_list(Id)}, 
			{question, Question},
			{answer, Answer},
			{correction, Correction},
			{rating, Rating},
			{difficulty, Difficulty},
			{mark, Mark}, 
			{day, integer_to_list(Day)}, 
			{month, integer_to_list(Month)},
			{year, integer_to_list(Year)}, 
			{hour, integer_to_list(Hour)}, 
			{minute, integer_to_list(Minute)}, 
			{teacher, atom_to_list(Teacher)}]}
			|| {atomic, 
				[{homework, Id, Question, Answer, Correction, Rating, Difficulty, Mark, 
				{{Year, Month, Day}, {Hour, Minute, _}}, Teacher, _}]} <- LHomeworks],
			
		{array, [TotalFinished | Data]}
	end.
